package com.campus.counseling.task;

import com.campus.counseling.entity.Appointment;
import com.campus.counseling.entity.ChatSession;
import com.campus.counseling.service.AppointmentService;
import com.campus.counseling.service.ChatService;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AppointmentScheduleTask {
    
    private final AppointmentService appointmentService;
    private final ChatService chatService;
    private final SimpMessagingTemplate messagingTemplate;
    
    // 每分钟检查一次预约
    @Scheduled(cron = "0 * * * * ?")
    public void checkUpcomingAppointments() {
        // 获取即将开始的预约（5-10分钟内）
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime tenMinutesLater = now.plusMinutes(10);
        
        List<Appointment> upcomingAppointments = appointmentService
            .getUpcomingAppointments(now, tenMinutesLater);
            
        for (Appointment appointment : upcomingAppointments) {
            // 创建聊天会话
            ChatSession session = chatService.getOrCreateSession(appointment.getId());
            
            // 发送系统通知
            String message = String.format("预约将在%d分钟后开始", 
                ChronoUnit.MINUTES.between(now, appointment.getAppointmentTime()));
                
            // 通知学生
            messagingTemplate.convertAndSendToUser(
                appointment.getStudentId().toString(),
                "/queue/notifications",
                message
            );
            
            // 通知咨询师
            messagingTemplate.convertAndSendToUser(
                appointment.getCounselorId().toString(),
                "/queue/notifications",
                message
            );
        }
    }
} 